//
//  FreebaseDetail.m
//  BandApp
//
//  Created by Alec Flett on 8/20/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FreebaseDetail.h"


@implementation FreebaseDetail
@synthesize fbs;
@synthesize imageView;
@synthesize nameLabel;
@synthesize aliasLabel;
@synthesize articleLabel;
@synthesize typeLabel = _typeLabel;

- (id)init
{
    NSLog(@"FreebaseDetail init");
    if ((self = [self initWithNibName:@"FreebaseDetail" bundle:nil])) {
        
    }
    return self;
}

- (void)dealloc {
    [super dealloc];
    [fbs release];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    if (!fbs)
        self.fbs = [FreebaseSession session];
    NSLog(@"Creating FreebaseDetail, fbs = %@", self.fbs);
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}
- (void)loadItemDetail: (NSDictionary *)itemData {
    
    if (itemData) {
        BOOL load_data = NO;
        
        NSString *name = [itemData objectForKey:@"name"];
        self.nameLabel.text = name;
        
        NSDictionary *image_data = [itemData objectForKey:@"/common/topic/image"];
        [self loadImage:image_data];
        
        NSDictionary *blurb_data = [itemData objectForKey:@"/common/topic/article"];
        [self loadBlurb:blurb_data];
        
        // this sucks, this is *trying* to make up for the fact that type could be
        // "/common/topic", ["/common/topic"], or [{"name": "Topic", "id": "/common/topic"}]
        id types = [itemData objectForKey:@"type"];
        if (!types || [types isKindOfClass:[NSArray class]])
            [self setTypeList:types];
        else if ([types isKindOfClass:[NSString class]])
            [self setTypeList:[NSArray arrayWithObject:[NSDictionary dictionaryWithObject:types forKey:@"name"]]];
        else
            [self setTypeList:[NSArray arrayWithObject:types]];

        load_data = !name || !image_data || !blurb_data || !types;
        
        NSString* item_id = [itemData objectForKey:@"id"];
        if (load_data && item_id)
            [self loadData:item_id];
    }
}

- (void)loadData:(NSString*)item_id
{
    NSLog(@"Loading data for %@ using %@", item_id, self.fbs);
    NSDictionary *q = [NSDictionary dictionaryWithObjectsAndKeys:
                       item_id, @"id",
                       [NSNull null], @"name",
                       [NSArray arrayWithObject:
                        [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNull null], @"id",
                         [NSNull null], @"name",
                         [NSNumber numberWithBool:YES], @"optional",
                         nil]], @"type",
                       [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNull null], @"guid",
                        [NSNumber numberWithInteger:1], @"limit",
                        [NSNumber numberWithBool:YES], @"optional",
                        nil],
                       @"/common/topic/article", 

                       
                       [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNull null], @"guid",
                        [NSNumber numberWithInteger:1], @"limit",
                        [NSNumber numberWithBool:YES], @"optional",
                        nil],                        
                       @"/common/topic/image", 
                       nil];
    [fbs mqlread:q
            name:@"item_detail" 
        delegate:self 
didFinishSelector:@selector(detailLoaded:)];
    
}

- (void)detailLoaded:(id)result
{
    NSDictionary *resultDict = result;
    self.nameLabel.text = [resultDict objectForKey:@"name"];
    [self setTypeList:[resultDict objectForKey:@"type"]];
    [self loadBlurb:[resultDict objectForKey:@"/common/topic/article"]];
    [self loadImage:[resultDict objectForKey:@"/common/topic/image"]];
}

- (void)setTypeList:(NSArray *)typeList
{
    NSArray* typeNames = [typeList valueForKeyPath:@"name"];
    NSMutableArray* filteredTypes = [NSMutableArray arrayWithCapacity:[typeNames count]];
    for (NSString* typeName in typeNames)
        if (![typeName isEqualToString:@"Topic"])
            [filteredTypes addObject:typeName];
    self.typeLabel.text = [filteredTypes componentsJoinedByString:@", "];

}

- (void)loadBlurb:(NSDictionary*) blurb_data
{
    if (!blurb_data || (NSObject*)blurb_data == [NSNull null]) {
        [self blurbLoaded:@""];
        return;
    }
    
    NSString *blurb_guid = [blurb_data objectForKey:@"guid"];
    NSString *blurb_id = [NSString stringWithFormat:@"/guid/%@", 
                          [blurb_guid substringFromIndex:1]];
    
    [fbs blurb:blurb_id 
          name:@"item_blurb" 
      delegate:self 
didFinishSelector:@selector(blurbLoaded:) 
       options:nil];
}

- (void)blurbLoaded:(NSString*)blurb
{
    self.articleLabel.text = blurb;
}

- (void)loadImage:(NSDictionary*)image_data
{
    if (!image_data || (NSObject*)image_data == [NSNull null]) {
        // here's where we'd put a blank image, or just 
        // remove the image view entirely
        [self imageLoaded:nil];
        return;
    }
    
    NSString *image_guid = [image_data objectForKey:@"guid"];
    NSString *image_id = [NSString stringWithFormat:@"/guid/%@", 
                          [image_guid substringFromIndex:1]];
    NSString* maxwidth = [NSString stringWithFormat:@"%d", 100];
    NSString* maxheight = [NSString stringWithFormat:@"%d", 100];
    
    [fbs imageThumb:image_id name:@"item_image" 
           delegate:self
  didFinishSelector:@selector(imageLoaded:) 
            options:[NSDictionary dictionaryWithObjectsAndKeys:maxwidth, @"maxwidth",
                     maxheight, @"maxheight", nil]];
}

- (void)imageLoaded:(NSData *)imageData
{
    UIImage *image = [UIImage imageWithData:imageData];
    
    self.imageView.image = image;
}

- (void)errorDidOccur:(id)error request:(id<FreebaseRequest>)request
{
    NSLog(@"error loading detail in %@: %@", request.name, error);
}

@end
